package util

import (
	"fmt"
	"strings"
	"time"
)

func VariableData(data string) string {
	if data == "" {
		return "0"
	}
	return data
}

func PopData(data string, length int) (string, string) {
	if data == "" || len(data) < length {
		return "", ""
	}
	d := []rune(data)
	popData := string(d[:length])
	lessData := string(d[length:])
	return lessData, popData
}

func MesTwo(data string) (string, string) {
	return PopData(data, 2)
}

func TransactionDate(data string) (string, string) {
	return PopData(data, 18)
}

func ParseTransactionDate(dateStr string) (time.Time, error) {
	// 定义固定的长度和格式
	fixedLength := 18
	formatString := "20060102    150405"

	// 验证字符串长度是否符合要求
	if len(dateStr) != fixedLength {
		return time.Time{}, fmt.Errorf("transaction date must be exactly 18 characters long")
	}

	// 尝试解析日期时间部分
	parsedDate, err := time.Parse(formatString, dateStr[:8]+"     "+dateStr[12:])
	if err != nil {
		return time.Time{}, fmt.Errorf("invalid transaction date format: %v", err)
	}

	// 返回解析后的日期时间对象
	return parsedDate, nil
}

func GetCurrentTimeInFormat() string {
	// 获取当前的日期和时间
	now := time.Now()

	// 格式化日期时间
	formattedTime := now.Format("20060102     150405")

	return formattedTime
}

func GetFormattedDatesAndTime() (string, string, string, string) {
	// 获取当前日期
	currentDate := time.Now().Format("20060102")
	// 获取30天后的日期
	dateIn30Days := time.Now().AddDate(0, 0, 30).Format("20060102")
	// 获取当前时间
	currentTime := time.Now().Format("15:04:05")
	// 获取当前日期和时间
	currentDateTime := time.Now().Format("2006-01-02     15:04:05")

	return currentDate, dateIn30Days, currentTime, currentDateTime
}

func ExtractValuesAndFormatV2(keysStr, inputString string) map[string]string {
	keys := strings.Split(keysStr, "|")
	parts := strings.Split(inputString, "|")

	keyValueDict := make(map[string]string)
	for _, part := range parts {
		for _, key := range keys {
			if strings.HasPrefix(part, key) {
				keyValueDict[key] = part[len(key):]
				break
			}
		}
	}

	for _, key := range keys {
		if _, ok := keyValueDict[key]; !ok {
			keyValueDict[key] = ""
		}
	}

	return keyValueDict
}
